import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		token: '',
		userInfo: null,
		isLogin: false
	},
	mutations: {
		// 设置token
		setToken(state, token) {
			state.token = token
			state.isLogin = !!token
			// 持久化存储
			if (token) {
				uni.setStorageSync('token', token)
			} else {
				uni.removeStorageSync('token')
			}
		},
		// 设置用户信息
		setUserInfo(state, userInfo) {
			state.userInfo = userInfo
			// 持久化存储
			if (userInfo) {
				uni.setStorageSync('userInfo', userInfo)
			} else {
				uni.removeStorageSync('userInfo')
			}
		},
		// 清除登录信息
		clearAuth(state) {
			state.token = ''
			state.userInfo = null
			state.isLogin = false
			uni.removeStorageSync('token')
			uni.removeStorageSync('userInfo')
		}
	},
	actions: {
		// 登录
		async login({ commit }, { username, password }) {
			try {
				const res = await this._vm.$api.login({ username, password })
				if (res.code === 200) {
					commit('setToken', res.data.token)
					commit('setUserInfo', res.data.user)
					return res
				} else {
					throw new Error(res.message)
				}
			} catch (error) {
				throw error
			}
		},
		// 退出登录
		async logout({ commit }) {
			try {
				await this._vm.$api.logout()
				commit('clearAuth')
			} catch (error) {
				// 即使接口失败也清除本地数据
				commit('clearAuth')
			}
		},
		// 获取用户信息
		async getUserInfo({ commit, state }) {
			try {
				const res = await this._vm.$api.getUserInfo()
				if (res.code === 200) {
					commit('setUserInfo', res.data)
					return res.data
				}
			} catch (error) {
				// 获取用户信息失败，可能token过期
				commit('clearAuth')
				throw error
			}
		}
	},
	getters: {
		// 是否已登录
		isLogin: state => state.isLogin,
		// 用户角色类型
		roleType: state => state.userInfo ? state.userInfo.roleType : null,
		// 用户角色名称
		roleName: state => {
			if (!state.userInfo) return ''
			switch (state.userInfo.roleType) {
				case 1: return '管理员'
				case 2: return '派单员'
				case 3: return '用户'
				case 4: return '技术员'
				default: return '未知'
			}
		},
		// 是否为管理员
		isAdmin: state => state.userInfo && state.userInfo.roleType === 1,
		// 是否为派单员
		isDispatcher: state => state.userInfo && state.userInfo.roleType === 2,
		// 是否为用户
		isUser: state => state.userInfo && state.userInfo.roleType === 3,
		// 是否为技术员
		isTech: state => state.userInfo && state.userInfo.roleType === 4,
		// 用户信息
		userInfo: state => state.userInfo
	}
})

export default store